﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using DTO;
using BUS;
using System.Collections.Generic;
using System.Xml;

namespace WebRaoVat
{
    public class CapDanhMucCon
    {
        private int _maDanhMuc;
        public int MaDanhMuc
        {
            get { return _maDanhMuc; }
            set { _maDanhMuc = value; }
        }

        private string _tenDanhMuc;
        public string TenDanhMuc
        {
            get { return _tenDanhMuc; }
            set { _tenDanhMuc = value; }
        }

        private int _soLuong;
        public int SoLuong
        {
            get { return _soLuong; }
            set { _soLuong = value; }
        }
    }

    public partial class TimKiem : System.Web.UI.Page
    {
        public List<string> ListMessage = new List<string>();
        public List<TinRaoVatDTO> DS = new List<TinRaoVatDTO>();
        public List<TinRaoVatDTO> DSTinRaoVatTheoMuc = new List<TinRaoVatDTO>();
        public string TenDanhMucConHienHanh = "";
        public List<CapDanhMucCon> DSCapDanhMucCon = new List<CapDanhMucCon>();
        private string MaTimKiem = "";
        private string ChuoiTimKiem = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["LoaiTimKiem"] == null || Session["LoaiTimKiem"].ToString().Length <= 0)
            {
                Response.Redirect("Default.aspx");
            }

            //Session["TrangHienTai"] = "TimKiem.aspx";
            if (Request.QueryString["MaTimKiem"] != null && Request.QueryString["MaTimKiem"].Length > 0)
            {
                MaTimKiem = Request.QueryString["MaTimKiem"].ToString();
            }

            if (Session["ChuoiTimKiem"] != null && Session["ChuoiTimKiem"].ToString().Length > 0)
            {
                ChuoiTimKiem = Session["ChuoiTimKiem"].ToString();
            }

            if (!IsPostBack)
            {
                int ChiSoDanhMuc = 0;
                int ChiSoDiaDiem = 0;

                txtSearch1.Text = ChuoiTimKiem;

                //Tìm kiếm nâng cao
                txtTenRaoVat.Text = Config._TenTinRaoVat;
                txtNoiDungRaoVat.Text = Config._NoiDungTinRaoVat;

                ddlDiaDiem.Items.Add("......");
                List<DiaDiemDTO> DSDiaDiem = DiaDiemBUS.getAll();

                for (int i = 0; i < DSDiaDiem.Count; ++i)
                {
                    ddlDiaDiem.Items.Add(DSDiaDiem[i].TenDiaDiem);
                }

                for (int i = 0; i < ddlDiaDiem.Items.Count; ++i)
                {
                    if (ddlDiaDiem.Items[i].Value.CompareTo(Config._TenDiaDiem) == 0)
                    {
                        ChiSoDiaDiem = i;
                        break;
                    }
                }

                ddlDiaDiem.SelectedIndex = ChiSoDiaDiem;

                ddlDanhMuc.Items.Add("......");
                List<DanhMucConDTO> DSDanhMucCon = DanhMucConBUS.getAll();

                for (int i = 0; i < DSDanhMucCon.Count; ++i)
                {
                    if (i > 4)
                    {
                        ddlDanhMuc.Items.Add(DSDanhMucCon[i].TenDanhMucCon);
                    }
                }

                for (int i = 0; i < ddlDanhMuc.Items.Count; ++i)
                {
                    if (ddlDanhMuc.Items[i].Value.CompareTo(Config._TenDanhMucCon) == 0)
                    {
                        ChiSoDanhMuc = i;
                        break;
                    }
                }

                ddlDanhMuc.SelectedIndex = ChiSoDanhMuc;

                txtGiaTu.Text = Config._GiaTu.ToString();
                txtGiaDen.Text = Config._GiaDen.ToString();

                //Ngày tháng từ và đến
                #region Ngay thang tu va den

                for (int i = 0; i < 31; ++i)
                {
                    ddlNgayTu.Items.Add((i + 1).ToString());
                    ddlNgayDen.Items.Add((i + 1).ToString());
                }

                int ChiSoNgayTu = 0;
                int ChiSoNgayDen = 0;

                for (int i = 0; i < 31; ++i)
                {
                    if (ddlNgayTu.Items[i].Value == (Config._ThoiGianTu.Day.ToString()))
                    {
                        ChiSoNgayTu = i;
                    }

                    if (ddlNgayDen.Items[i].Value == (Config._ThoiGianDen.Day.ToString()))
                    {
                        ChiSoNgayDen = i;
                    }
                }

                ddlNgayTu.SelectedIndex = ChiSoNgayTu;
                ddlNgayDen.SelectedIndex = ChiSoNgayDen;

                for (int i = 0; i < 12; ++i)
                {
                    ddlThangTu.Items.Add((i + 1).ToString());
                    ddlThangDen.Items.Add((i + 1).ToString());
                }

                int ChiSoThangTu = 0;
                int ChiSoThangDen = 0;

                for (int i = 0; i < 12; ++i)
                {
                    if (ddlThangTu.Items[i].Value == (Config._ThoiGianTu.Month.ToString()))
                    {
                        ChiSoThangTu = i;
                    }

                    if (ddlThangDen.Items[i].Value == (Config._ThoiGianDen.Month.ToString()))
                    {
                        ChiSoThangDen = i;
                    }
                }

                ddlThangTu.SelectedIndex = ChiSoThangTu;
                ddlThangDen.SelectedIndex = ChiSoThangDen;

                for (int i = 0; i < 101; ++i)
                {
                    ddlNamTu.Items.Add((i + 2000).ToString());
                    ddlNamDen.Items.Add((i + 2000).ToString());
                }

                int ChiSoNamTu = 0;
                int ChiSoNamDen = 0;

                for (int i = 0; i < 101; ++i)
                {
                    if (ddlNamTu.Items[i].Value == (Config._ThoiGianTu.Year.ToString()))
                    {
                        ChiSoNamTu = i;
                    }

                    if (ddlNamDen.Items[i].Value == (Config._ThoiGianDen.Year.ToString()))
                    {
                        ChiSoNamDen = i;
                    }
                }

                ddlNamTu.SelectedIndex = ChiSoNamTu;
                ddlNamDen.SelectedIndex = ChiSoNamDen;

                #endregion

                this.BindItemsList();
            }
        }

        protected void Page_PreInit(object sender, EventArgs e)
        {
            Page.Theme = ((XmlElement)XL_XML.ReadNodeSingle(XL_XML.ReadDocumentFile(Server.MapPath("Gui.xml")),
            "/GIAODIEN/THEME")).GetAttribute("ten");
        }

        #region Private Properties

        private int CurrentPage
        {
            get
            {
                object objPage = ViewState["_CurrentPage"];
                int _CurrentPage = 0;

                if (objPage == null)
                {
                    _CurrentPage = 0;
                }
                else
                {
                    _CurrentPage = (int)objPage;
                }

                return _CurrentPage;
            }

            set { ViewState["_CurrentPage"] = value; }
        }

        private int fistIndex
        {
            get
            {
                int _FirstIndex = 0;

                if (ViewState["_FirstIndex"] == null)
                {
                    _FirstIndex = 0;
                }
                else
                {
                    _FirstIndex = Convert.ToInt32(ViewState["_FirstIndex"]);
                }

                return _FirstIndex;
            }

            set { ViewState["_FirstIndex"] = value; }
        }

        private int lastIndex
        {
            get
            {
                int _LastIndex = 0;

                if (ViewState["_LastIndex"] == null)
                {
                    _LastIndex = 0;
                }
                else
                {
                    _LastIndex = Convert.ToInt32(ViewState["_LastIndex"]);
                }

                return _LastIndex;
            }

            set { ViewState["_LastIndex"] = value; }
        }

        #endregion

        #region PagedDataSource
        PagedDataSource _PageDataSource = new PagedDataSource();
        #endregion

        #region Private Methods

        /// <summary>
        /// Build DataTable to bind Main Items List
        /// </summary>
        /// <returns>DataTable</returns>
        private DataTable GetDataTable()
        {
            DataTable dtItems = new DataTable();

            DataColumn dcName = new DataColumn();
            dcName.ColumnName = "title";
            dcName.DataType = System.Type.GetType("System.String");
            dtItems.Columns.Add(dcName);

            DataRow row;
            for (int i = 1; i <= 100; i++)
            {
                row = dtItems.NewRow();
                row["title"] = "hmweb - Phân Trang dữ liệu DataList: &nbsp;Đây là bản ghi thứ " + i;
                dtItems.Rows.Add(row);
            }

            return dtItems;
        }

        private List<CapDanhMucCon> ChiaRaTheoDanhMucCon(List<TinRaoVatDTO> DS)
        {
            List<CapDanhMucCon> Result = new List<CapDanhMucCon>();
            List<DanhMucConDTO> DSDanhMucCon = DanhMucConBUS.getAll();

            for (int i = 0; i < DSDanhMucCon.Count; ++i)
            {
                int SoLuong = 0;
                int MaDanhMucCon = DSDanhMucCon[i].MaDanhMucCon;

                for (int j = 0; j < DS.Count; ++j)
                {
                    if (MaDanhMucCon == DS[j].MaDanhMucCon)
                    {
                        SoLuong++;
                    }
                }

                if (SoLuong > 0)
                {
                    CapDanhMucCon Temp = new CapDanhMucCon();
                    Temp.MaDanhMuc = DSDanhMucCon[i].MaDanhMucCon;
                    Temp.TenDanhMuc = DSDanhMucCon[i].TenDanhMucCon;
                    Temp.SoLuong = SoLuong;

                    Result.Add(Temp);
                }
            }

            return Result;
        }

        private List<TinRaoVatDTO> LayDSTinRaoVatTheoMuc(List<TinRaoVatDTO> DSTinRaoVat, int MaDanhMuc)
        {
            List<TinRaoVatDTO> Result = new List<TinRaoVatDTO>();

            for (int i = 0; i < DSTinRaoVat.Count; ++i)
            {
                if (DSTinRaoVat[i].MaDanhMucCon == MaDanhMuc)
                {
                    Result.Add(DSTinRaoVat[i]);
                }
            }

            return Result;
        }

        /// <summary>
        /// Binding Main Items List
        /// </summary>
        private void BindItemsList()
        {
            DS.Clear();
            DSTinRaoVatTheoMuc.Clear();
            DataTable dataTable = this.GetDataTable();

            if (Session["LoaiTimKiem"].ToString() == "1")
            {
                DS = TinRaoVatBUS.Search(ChuoiTimKiem);
            }
            else
            {
                DS = TinRaoVatBUS.SearchNangCao(Config._TenTinRaoVat, Config._NoiDungTinRaoVat,
                    Config._TenDanhMucCon, Config._TenDiaDiem,
                    Config._GiaTu, Config._GiaDen,
                    Config._ThoiGianTu, Config._ThoiGianDen);
            }

            //Chia ra theo danh mục con
            DSCapDanhMucCon.Clear();
            DSCapDanhMucCon = ChiaRaTheoDanhMucCon(DS);
            DSTinRaoVatTheoMuc = LayDSTinRaoVatTheoMuc(DS, int.Parse(MaTimKiem));

            try
            {
                TenDanhMucConHienHanh = DanhMucConBUS.getTenDanhMuc(int.Parse(MaTimKiem));
            }
            catch (System.Exception ex)
            {
                TenDanhMucConHienHanh = "";
            }

            if (DSCapDanhMucCon.Count > 0 && MaTimKiem == "-1")
            {
                TenDanhMucConHienHanh = DSCapDanhMucCon[0].TenDanhMuc;
                DSTinRaoVatTheoMuc = LayDSTinRaoVatTheoMuc(DS, DSCapDanhMucCon[0].MaDanhMuc);
            }

            _PageDataSource.DataSource = DSTinRaoVatTheoMuc;

            _PageDataSource.AllowPaging = true;
            _PageDataSource.PageSize = 10;
            _PageDataSource.CurrentPageIndex = CurrentPage;
            ViewState["TotalPages"] = _PageDataSource.PageCount;

            this.lblPageInfo.Text = "Trang " + (CurrentPage + 1) + " của " + _PageDataSource.PageCount;
            this.lbtnPrevious.Enabled = !_PageDataSource.IsFirstPage;
            this.lbtnNext.Enabled = !_PageDataSource.IsLastPage;
            this.lbtnFirst.Enabled = !_PageDataSource.IsFirstPage;
            this.lbtnLast.Enabled = !_PageDataSource.IsLastPage;

            this.DataList1.DataSource = _PageDataSource;
            this.DataList1.DataBind();
            this.doPaging();
        }

        /// <summary>
        /// Binding Paging List
        /// </summary>
        private void doPaging()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("PageIndex");
            dt.Columns.Add("PageText");
            fistIndex = CurrentPage - 5;

            if (CurrentPage > 5)
            {
                lastIndex = CurrentPage + 5;
            }
            else
            {
                lastIndex = 10;
            }

            if (lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
            {
                lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                fistIndex = lastIndex - 10;
            }

            if (fistIndex < 0)
            {
                fistIndex = 0;
            }

            for (int i = fistIndex; i < lastIndex; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i + 1;
                dt.Rows.Add(dr);
            }

            this.dlPaging.DataSource = dt;
            this.dlPaging.DataBind();
        }

        #endregion

        protected void lbtnNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            this.BindItemsList();
        }

        protected void lbtnPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            this.BindItemsList();
        }

        protected void lbtnLast_Click(object sender, EventArgs e)
        {
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
            this.BindItemsList();
        }

        protected void lbtnFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            this.BindItemsList();
        }

        protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName.Equals("Paging"))
            {
                CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
                this.BindItemsList();
            }
        }

        protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            LinkButton lnkbtnPage = (LinkButton)e.Item.FindControl("lnkbtnPaging");
            if (lnkbtnPage.CommandArgument.ToString() == CurrentPage.ToString())
            {
                lnkbtnPage.Enabled = false;
                lnkbtnPage.Style.Add("fone-size", "14px");
                lnkbtnPage.Font.Bold = true;

            }
        }

        protected void btnSearch1_Click(object sender, EventArgs e)
        {
            Session["LoaiTimKiem"] = 1;
            Session["ChuoiTimKiem"] = txtSearch1.Text.Trim().ToLower();
            Response.Redirect("TimKiem.aspx?MaTimKiem=-1");
        }

        protected void btnSearch2_Click(object sender, EventArgs e)
        {
            Session["LoaiTimKiem"] = 2;

            ListMessage.Clear();

            Config._TenTinRaoVat = txtTenRaoVat.Text.Trim().ToLower();
            Config._NoiDungTinRaoVat = txtNoiDungRaoVat.Text.Trim().ToLower();
            Config._TenDanhMucCon = ddlDanhMuc.SelectedValue;
            Config._TenDiaDiem = ddlDiaDiem.SelectedValue;

            try
            {
                Config._GiaTu = int.Parse(txtGiaTu.Text.Trim());
            }
            catch (System.Exception ex)
            {
                ListMessage.Add("* Giá từ chỉ được là số");
                return;
            }

            try
            {
                Config._GiaDen = int.Parse(txtGiaDen.Text.Trim());
            }
            catch (System.Exception ex)
            {
                ListMessage.Add("* Giá đến chỉ được là số");
                return;
            }

            try
            {
                Config._ThoiGianTu = new DateTime(int.Parse(ddlNamTu.SelectedValue),
                    int.Parse(ddlThangTu.SelectedValue),
                    int.Parse(ddlNgayTu.SelectedValue));

                Config._ThoiGianDen = new DateTime(int.Parse(ddlNamDen.SelectedValue),
                    int.Parse(ddlThangDen.SelectedValue),
                    int.Parse(ddlNgayDen.SelectedValue));
            }
            catch (System.Exception ex)
            {
                ListMessage.Add("* Thời gian từ (đến) không hợp lệ");
                return;
            }

            Response.Redirect("TimKiem.aspx?MaTimKiem=-1");
        }
    }
}
